<template>
  <div class="links-view">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-xl font-semibold">短链接管理</h2>
      <div class="flex gap-2">
        <el-button type="primary" @click="showDialog = true">
          创建短链接
        </el-button>
        <el-button 
          type="success" 
          @click="$router.push('/admin/weapp')"
          v-if="$route.path !== '/admin/weapp'">
          小程序管理
        </el-button>
      </div>
    </div>

    <el-table :data="links" border stripe>
      <el-table-column prop="shortUrl" label="短链接" width="200">
        <template #default="{row}">
          <a :href="row.shortUrl" target="_blank" class="text-blue-500 hover:underline">
            {{ row.shortUrl }}
          </a>
        </template>
      </el-table-column>
      <el-table-column prop="originalUrl" label="原始链接" />
      <el-table-column prop="redirectType" label="跳转类型" width="120">
        <template #default="{row}">
          <el-tag :type="row.redirectType === 'http' ? '' : 'success'">
            {{ 
              row.redirectType === 'http' ? '普通HTTP' : 
              row.redirectType === 'weapp_scheme' ? '小程序Scheme' : '小程序URLLink'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="expireTime" label="过期时间" width="180">
        <template #default="{row}">
          {{ row.expireTime ? new Date(row.expireTime).toLocaleString() : '永久有效' }}
        </template>
      </el-table-column>
      <el-table-column prop="clicks" label="点击量" width="100" />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column label="操作" width="180">
        <template #default="{row}">
          <el-button size="small" @click="editLink(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteLink(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="showDialog" :title="dialogTitle" width="50%">
      <el-form :model="form" label-width="100px">
        <el-form-item label="原始链接" required>
          <el-input v-model="form.originalUrl" placeholder="请输入原始链接" />
        </el-form-item>
        <el-form-item label="自定义短链">
          <el-input v-model="form.customPath" placeholder="可选: 自定义路径" />
        </el-form-item>
        <el-form-item label="跳转类型">
          <el-select v-model="form.redirectType" placeholder="请选择跳转类型">
            <el-option label="普通HTTP" value="http" />
            <el-option label="微信小程序Scheme" value="weapp_scheme" />
            <el-option label="微信URLLink" value="weapp_urllink" />
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" v-if="form.redirectType === 'weapp_scheme' || form.redirectType === 'weapp_urllink'">
          <el-date-picker
            v-model="form.expireTime"
            type="datetime"
            placeholder="选择过期时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, defineProps } from 'vue'
defineProps({
  isDark: Boolean
})
import { ElButton, ElTable, ElTableColumn, ElDialog, ElForm, ElFormItem, ElInput, ElMessage, ElMessageBox, ElTag, ElDatePicker } from 'element-plus'

const links = ref([
  {
    id: 1,
    shortUrl: 'https://short.ly/abc123',
    originalUrl: 'https://example.com/long/url/path',
    redirectType: 'http',
    expireTime: null,
    clicks: 42,
    createdAt: '2025-03-27'
  },
  {
    id: 2,
    shortUrl: 'https://short.ly/def456',
    originalUrl: 'https://another-example.com/very/long/url',
    redirectType: 'weapp_scheme',
    expireTime: '2025-04-28T12:00:00',
    clicks: 15,
    createdAt: '2025-03-28'
  }
])

const showDialog = ref(false)
const isEditing = ref(false)
const currentId = ref(null)

const form = ref({
  originalUrl: '',
  customPath: '',
  redirectType: 'http',
  expireTime: null
})

const dialogTitle = computed(() => {
  return isEditing.value ? '编辑短链接' : '创建短链接'
})

function editLink(link) {
  isEditing.value = true
  currentId.value = link.id
  form.value = {
    originalUrl: link.originalUrl,
    customPath: link.shortUrl.split('/').pop(),
    redirectType: link.redirectType || 'http',
    expireTime: link.expireTime || null
  }
  showDialog.value = true
}

function deleteLink(id) {
  ElMessageBox.confirm('确定要删除这个短链接吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    links.value = links.value.filter(link => link.id !== id)
    ElMessage.success('删除成功')
  })
}

function submitForm() {
  if (!form.value.originalUrl) {
    ElMessage.error('请输入原始链接')
    return
  }

  const domain = 'https://short.ly/'
  const path = form.value.customPath || Math.random().toString(36).substring(2, 8)

  if (isEditing.value) {
    const index = links.value.findIndex(link => link.id === currentId.value)
    if (index !== -1) {
      links.value[index] = {
        ...links.value[index],
        originalUrl: form.value.originalUrl,
        shortUrl: domain + path
      }
    }
    ElMessage.success('更新成功')
  } else {
    links.value.push({
      id: Date.now(),
      shortUrl: domain + path,
      originalUrl: form.value.originalUrl,
      redirectType: form.value.redirectType,
      expireTime: form.value.expireTime,
      clicks: 0,
      createdAt: new Date().toISOString().split('T')[0]
    })
    ElMessage.success('创建成功')
  }

  showDialog.value = false
  resetForm()
}

function resetForm() {
  form.value = {
    originalUrl: '',
    customPath: '',
    redirectType: 'http',
    expireTime: null
  }
  isEditing.value = false
  currentId.value = null
}
</script>

<style scoped>
.links-view {
  padding: 20px;
}

.el-table {
  margin-top: 20px;
}
</style>
